import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'
// import Vue from 'vue'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 2000000
})

let isHasPop = false

// 请求拦截
service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  (response) => {
    const res = response.data || {}
    // 文件流
    if (Object.prototype.toString.call(response.data) === '[object Blob]') {
      return res
    }
    if (res.code !== '1000') {
      if (res.code === '9999') {
        return res
      }
      if (res.code === '500') {
        Message({
          message: '系统繁忙，请稍后再试！',
          type: 'error',
          duration: 2 * 1000
        })
        return res
      }
      if (res.code === '401') {
        // 无权限
        Message.error('无权限访问！')
      }
      if (['600', '011', '012'].includes(res.code)) {
        Message({
          message: res.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
        return res
      }
      if (['900'].includes(res.code)) {
        Message({
          message: res.msg || 'Error',
          type: 'error',
          duration: 2 * 1000
        })
        return res
      }
      // 收到关闭异常提示 910 导入报错
      if (res.code === '910') {
        const msg = JSON.parse(res.msg)
        let htmlStr = ''
        if (!res.msg || !Array.isArray(msg)) {
          htmlStr = `<div>${msg}</div></br>`
        } else {
          msg.forEach((e) => {
            htmlStr += `<div>${e}</div>`
          })
        }
        MessageBox.confirm(htmlStr, '异常提示', {
          showCancelButton: false,
          showConfirmButton: false,
          dangerouslyUseHTMLString: true,
          type: 'warning',
          customClass: 'set-max-height50 width-50'
        }).then(() => {
          return
        })
      }
      if (res.code === '000') {
        if (isHasPop) {
          return
        }
        isHasPop = true
        MessageBox.confirm('登录信息失效，请重新登录', '异常提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            isHasPop = false
            // location.reload()
            router.push('/login')
            return
          })
          .catch(() => {
            isHasPop = false
          })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  (error) => {
    console.log('err' + error)
    Message({
      message: '请求异常，请稍后重试',
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
